<template>
    <img ref="imgRef" :src="props.src" @click="state.popShown = true" v-bind="$attrs" class="img" />
    <a-modal v-model:value="state.popShown" :clickBgToClose="true">
        <img
            ref="popImgRef"
            :src="props.src"
            @click.left="state.popShown = false"
            @wheel="methods.onWheel"
            style="max-width: 50%; max-height: 50%; transform: scale(1, 1); transition: transform 200ms"
        />
    </a-modal>
</template>

<style lang="scss" scoped>
.img {
    object-fit: scale-down;
}
</style>

<script setup lang="ts">
import { reactive, ref, watchEffect } from 'vue'
import AModal from './AModal.vue'

interface PropsType {
    src: string
}
const props = withDefaults(defineProps<PropsType>(), {})

interface StateType {
    popShown: boolean
}
const state = reactive<StateType>({
    popShown: false,
})

const imgRef = ref<HTMLImageElement>()
const popImgRef = ref<HTMLImageElement>()
const emit = defineEmits<{
    (e: 'info', value: { width: number; height: number }): void
}>()

const methods = {
    onLoad() {
        let imgEl = imgRef.value!
        let oWidth = imgEl.naturalWidth
        let oHeight = imgEl.naturalHeight

        emit('info', {
            width: oWidth,
            height: oHeight,
        })
    },
    onWheel(e: WheelEvent) {
        let popImg = popImgRef.value!
        let toAddFactor = e.deltaY < 0 ? 0.1 : -0.1
        let transform = popImg.style.transform
        let scaleStr = transform.substring(transform.indexOf('(') + 1, transform.indexOf(','))
        let scale = Number.parseFloat(scaleStr)
        let newScale = scale + toAddFactor
        let newTransform = `scale(${newScale}, ${newScale})`
        popImg.style.transform = newTransform
    },
}

watchEffect(() => {
    imgRef.value?.addEventListener('load', methods.onLoad)
})
</script>
